package com.shushan.db;

import android.content.Context;
import android.util.Log;


import com.j256.ormlite.dao.Dao;
import com.shushan.login.bean.UserBean;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UserBeanDao
 * @Desciption: 定义UserBean数据访问对象，对指定的表进行增删改查操作
 * @author: yichaohua
 * @date: 2018-05-21
 */
public class UserBeanDao {
    private static final String TAG = "UserBeanDao";

    private Dao<UserBean, Integer> UserBeanDao;
    private DBHelper dbHelper;

    /**
     * 构造方法
     * 获得数据库帮助类实例，通过传入Class对象得到相应的Dao
     * @param context
     */
    public UserBeanDao(Context context) {
        try {
            dbHelper = DBHelper.getHelper(context);
            UserBeanDao = dbHelper.getDao(UserBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if(UserBeanDao == null){
            Log.e(TAG,"childBeanDao == null");
        }
    }

    /**
     * 添加一条记录
     * @param userBean
     */
    public void add(UserBean userBean) {
        try {
            UserBeanDao.create(userBean);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除一条记录
     * @param userBean
     */
    public void delete(UserBean userBean) {
        try {
            UserBeanDao.delete(userBean);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新一条记录
     * @param userBean
     */
    public void update(UserBean userBean) {
        try {
            UserBeanDao.update(userBean);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询一条记录
     * @param id
     * @return
     */
    public UserBean queryForId(int id) {
        UserBean userBean = null;
        try {
            userBean = UserBeanDao.queryForId(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userBean;
    }

    /**
     * 查询所有记录
     * @return
     */
    public List<UserBean> queryForAll() {
        List<UserBean> userBeanList = new ArrayList<UserBean>();
        try {
            userBeanList = UserBeanDao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userBeanList;
    }

    public boolean contain(int id){
        List<UserBean> userBeanList = queryForAll();
        for (UserBean userBean : userBeanList){
            if(userBean.id == id){
                return true;
            }
        }

        return false;
    }

    public void clearTab(){
        try {
            UserBeanDao.queryRaw("delete from user_table");
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
